#include "List.cpp"

//给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。

ListNode *rotateRight(ListNode *head, int k) {
    if (head == NULL || head->next == NULL) {
        return head;
    }
    ListNode *newHead = (ListNode *) malloc(sizeof(ListNode));
    newHead->next = head;
    // 确定链表长度,找到尾结点
    ListNode *p = head;
    int length = 1;
    while (p->next != NULL) {
        length++;
        p = p->next;
    }
    ListNode *tail = p;
    // 确定分割点,如果不需要分割直接退出.
    int split = length - k % length;
    if (split == 0 || length == split) {
        return head;
    }
    // 找到分割点
    p = head;
    ListNode *pre = newHead;
    for (int i = 0; i < split; ++i) {
        p = p->next;
        pre = pre->next;
    }
    // 将分割点分离,链表尾部与头链接,分割点与新链表链接
    pre->next = NULL;
    tail->next = head;
    newHead->next = p;

    return newHead->next;
}

int main() {
    int number[] = {1, 2};
    List list = CreateListByArray(number, ARRAY_SIZE(number));
    List newList = rotateRight(list, 0);
    PrintList(newList);
}
